const { Controller } = require('varal');
const dayjs = require('dayjs');
const crypto = require('crypto');
const chance = require('chance').Chance();
const path = require('path');
const fs = require('fs');

class UtilController extends Controller {
	async oss() {
		const { accessKeyId, accessKeySecret, bucket, maxSize, expireTime, endpoint, domain } = this.app.config.oss;
		const dir = `eam/${dayjs().format('YYYYMM')}/`;
		const { name = '' } = this.app.fields;

		const payload = {
			expiration: dayjs().add(expireTime, 'minute').toISOString(),
			conditions: [
				['content-length-range', 0, maxSize * 1024 * 1024],
				['starts-with', '$key', dir]
			]
		}
		const policy = Buffer.from(JSON.stringify(payload)).toString('base64');
		const key = `${dir}${chance.string({ length: 32, alpha: true, numeric: true })}${path.extname(name)}`;
		this.app.json({
			err_code: 0,
			data: {
				host: `https://${bucket}.${endpoint}`,
				accessid: accessKeyId,
				policy,
				signature: crypto
					.createHmac('sha1', accessKeySecret)
					.update(policy)
					.digest()
					.toString('base64'),
				expire: payload.expiration,
				dir,
				key,
				url: `https://${domain}/${key}`
			}
		});
	}

	async upload() {
		const { files } = this.app;
		const file = files[0];

		//保存文件
		const dir = dayjs().format('YYYYMM');

		const uploadDir = path.resolve('public/uploadfile', dir);

		//判断目录是否存在
		if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir);

		const filename = `${chance.string({ length: 32, alpha: true, numeric: true })}${path.extname(file.originalFilename)}`;

		fs.writeFileSync(path.join(uploadDir, filename), fs.readFileSync(file.path));
		const url = `https://mp.kachewo.com/uploadfile/${dir}/${filename}`;

		return this.app.json({
			err_code: 0,
			data: {
				url
			}
		});
	}
}

exports = module.exports = UtilController;
